package top.icecola.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.icecola.community.domain.DiscussPost;
import top.icecola.community.domain.Page;
import top.icecola.community.domain.User;
import top.icecola.community.service.DiscussPostService;
import top.icecola.community.service.UserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @GetMapping("/alluser")
    public String allUsers(Page page, Model model){
        page.setRows(userService.selectAll().size());
        page.setPath("/alluser");
        page.setLimit(10);
        List<User> users = userService.selectAllUser(page.getCurrent(), page.getLimit());
        model.addAttribute("users",users);
        return "/site/users";
    }

    @RequestMapping("/searchname")
    public String searchName(String keyname, Page page, Model model){
        page.setPath("/searchname");
        page.setLimit(10);
        page.setRows(userService.searchUsernameSize(keyname));
        List<User> userList = userService.searchUsername(keyname, page.getCurrent(), page.getLimit());
        model.addAttribute("users",userList);
        return "/site/users";
    }
    @PostMapping("/active")
    public String active(Integer userId){
        userService.setStatus(userId,1);
        return "/site/users";
    }

    @PostMapping("/forbid")
    public String forbid(Integer userId){
        userService.setStatus(userId,0);
        return "/site/users";
    }

    @GetMapping("/deletePost")
    public String deletePost(Model model,Page page){
        if(discussPostService.deletePostRows()==0){
            page.setRows(0);
        }else{
            page.setRows(discussPostService.deletePostRows());
        }
        page.setPath("/deletePost");
        page.setLimit(5);
        List<DiscussPost> postList = discussPostService.deletePost(page.getCurrent(), page.getLimit());
        List<Map<String,Object>> mapList=new ArrayList<>();
        if(postList!=null){
            for(DiscussPost post:postList){
                Map<String,Object> map=new HashMap<>();
                map.put("post",post);
                User user = userService.findUserById(post.getUserId());
                map.put("user",user);
                mapList.add(map);
            }
        }
        model.addAttribute("userPosts",mapList);
        return "/site/delete-post";
    }

    @GetMapping("/reback")
    public String reback(Integer postId){
        discussPostService.setState(postId,0);
        return "/site/delete-post";
    }
}
